package com.xianggu.mybatis.mapper;

import com.xianggu.mybatis.mapper.entry.MybatisSqlVo;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.xianggu.mybatis.enums.SqlExecuteTypeEnum.getSqlExecuteTypeEnum;
import static com.xianggu.mybatis.mapper.demo.ForeachSqlParser.parseForeach;

public class MyBatisSqlParser {

    private static Map< String, Map<String, MybatisSqlVo>> sqlCacheMap = new HashMap<>();
    private static final String DYNAMIC_SQL_TAG = "if";
    private static final String DYNAMIC_SQL_TAG_END = "/if";



    public static void main(String[] args) {
        try {
            // 加载 XML 文件
            File xmlFile = new File("D:\\javaDemo\\xiangGu\\xiangGu\\Provider\\src\\main\\resources\\com\\xianggu\\mapper\\UserMapper.xml");
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(xmlFile);
// 模拟参数
            Map<String, Object> parameters = new HashMap<>();
            parameters.put("ids", List.of(1, 2, 3));

            // 获取根节点
            Element root = document.getDocumentElement();

            // 获取所有 SQL 语句
            NodeList nodeList = root.getChildNodes();
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    Element element = (Element) node;
                    String sqlId = element.getAttribute("id");
                    String sql = element.getTextContent().trim();

//                    sql = parseForeach(element, parameters);

                    // 处理动态 SQL
                    sql = parseDynamicSql(element, null);

                    // 替换参数
//                    Map<String, Object> parameters = new HashMap<>();
//                    parameters.put("id", 1);
//                    parameters.put("name", "John");
//                    sql = replaceParameters(sql, parameters);

                    System.out.println("SQL ID: " + sqlId);
                    System.out.println("SQL: " + sql);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 解析当前mapper文件对应的xml文件
    public static Map<String, MybatisSqlVo> parseMapperXml(String mapperXmlPath, Map<String, Object> paramMap) {
        if (sqlCacheMap.containsKey(mapperXmlPath)) {
            return sqlCacheMap.get(mapperXmlPath);
        }

        Map<String, MybatisSqlVo> sqlMap = new HashMap<>();

        try {
            // 加载 XML 文件
            File xmlFile = new File(mapperXmlPath);
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(xmlFile);

            // 获取根节点
            Element root = document.getDocumentElement();

            // 获取所有 SQL 语句
            NodeList nodeList = root.getChildNodes();
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    Element element = (Element) node;
                    String sqlId = element.getAttribute("id");
                    String sql = element.getTextContent().trim();

                    // 处理动态 SQL
                    sql = parseDynamicSql(element , paramMap);

                    MybatisSqlVo mybatisSqlVo = new MybatisSqlVo(sql, getSqlExecuteTypeEnum(node.getNodeName()) );
                    sqlMap.put(sqlId, mybatisSqlVo);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 缓存起来
        sqlCacheMap.put(mapperXmlPath, sqlMap);
        return sqlMap;
    }

    private static String parseDynamicSql(Element element, Map<String, Object> paramMap) {
        StringBuilder sql = new StringBuilder();
        NodeList children = element.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            Node node = children.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                Element childElement = (Element) node;
                String tagName = childElement.getTagName();
                if ("if".equals(tagName)) {
                    String condition = childElement.getAttribute("test");
                    String content = childElement.getTextContent().trim();
                    sql.append(" IF (").append(condition).append(") ").append(content);
                }
                // 处理其他动态 SQL 标签
            } else if (node.getNodeType() == Node.TEXT_NODE) {
                sql.append(node.getTextContent().trim());
            }
        }
        return sql.toString();
    }

    private static String replaceParameters(String sql, Map<String, Object> parameters) {
        for (Map.Entry<String, Object> entry : parameters.entrySet()) {
            String placeholder = "#{" + entry.getKey() + "}";
            sql = sql.replace(placeholder, entry.getValue().toString());
        }
        return sql;
    }
}